<?php
if ( page::$ajax ) {

} else {

    $elem = new Content();
    $parent = new Content();
    $add = true;
    if ( $elem->load( $id = page::url(1) ) ) {
      $add = false;
      $parent->load( $elem->id );
    } elseif (isset($_GET['to'] )) {
      $parent->load( $_GET['to'] );
    }

    switch ( isset($_GET['act']) ? $_GET['act'] : 'html' ) {
    case 'children':
      if ( isset( $_GET['delete'] ) && $delete = $_GET['delete']+0 ) {
        db::delete( 'content', $delete );
      }
      $sql = "SELECT * FROM `content` WHERE `parent`=':1'";
      $tmp = new Template('pan_children');
      $tmp->assign( 'children', db::q($sql, page::url(1)) );
      page::$html->assign( 'content', $tmp->process() );
      break;
      
      
    case 'editor':
      if ( mod::exists( $elem->type.'.editor' ) ) {
        page::$html->assign( 'content', mod::exec( $elem->type.'.editor' ) );
        break;
      }
    default:
      $form = new Form( 'content', !$add ? $elem->id : null );
      if ( $add && !empty($_GET['to']) ) {
        $form->hidden( 'parent', $_GET['to']+0, false );
      }
      $form->str( 'Page title', 'title' );
      $form->str( 'Code for URL', 'alias' );
      $form->str( 'Data type', 'type', isor($parent->child_type,'page') );
      $form->str( 'Child data type', 'child_type', 'page' );
      $form->str( 'template', 'template', $parent->template );
      $form->text( 'Text', 'data' );
      $form->check( 'Hide', 'hide' );
      $form->check( 'Show in menu', 'menu' );
      $form->submit('Save');
      $form->process();
      
      page::$html->assign( 'content', $form );
      if ( !empty($_POST['alias']) ) {
        $fp = $_POST['alias'];
        $sql = "SELECT `id`, `parent`, `alias`, `fullpath` FROM `content` WHERE `id`=':1'";
        $level = db::q( $sql, $form->id() );
        while ( $level->parent ) {
          $level = db::q( $sql, $level->parent );
          $fp = $level->alias . '/' . $fp;
        }
        db::q( "UPDATE `content` SET `fullpath`='::1' WHERE `id`=':i2'", $fp, $form->id() );
        if ( $elem->alias != $_POST['alias'] ) {
          $sql = "UPDATE `content` SET fullpath = CONCAT( '::1', SUBSTRING( fullpath, LENGTH( '::2/' ) ) ) WHERE fullpath LIKE '::2/%'";
          db::q( $sql, $fp, $elem->fullpath );
        }
      }
  }
  mod::exists( $elem->type.'.editor' ) && page::$html->add( 'tabs', array( 'link'=>'editor', 'caption'=>'Editing' ) );
  page::$html->add( 'tabs', array( 'link'=>'advanced', 'caption'=>'Advanced Editor' ) );
  page::$html->add( 'tabs', array( 'link'=>'children', 'caption'=>'Children' ) );
}